package com.mall.order.consumer.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.nio.charset.StandardCharsets;

/**
 * @author
 * @date 2020/12/26 11:17
 */
@Slf4j
@Component
public class OrderDelayMQProducer {

    DefaultMQProducer mqProducer;

    @PostConstruct
    public void init(){
        mqProducer = new DefaultMQProducer("order_group");
        mqProducer.setNamesrvAddr("127.0.0.1:9876");
        try {
            mqProducer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
        log.info("OrderMqProducer is start");
    }

    public boolean sendMessage(String orderId){
        Message message = new Message();
        message.setTopic("order_delay");
        message.setBody(orderId.getBytes(StandardCharsets.UTF_8));
        //设置消息的延迟级别 为5  1分钟
        //1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
        message.setDelayTimeLevel(5);
        try {
            SendResult result = mqProducer.send(message);
            SendStatus sendStatus = result.getSendStatus();
            String format = String.format("消息%s", sendStatus);
            log.info(format);
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return true;
    }

    @PreDestroy
    public void destroy(){
//        mqProducer.shutdown();
    }

}
